"""This module provides mydouyn"""
import time
import json
import random
import os
import platform
from auto.sleep.data import go_to_sleep
from auto.sleep.data import get_pitcute
import traceback
import datetime
from playwright.sync_api import sync_playwright
from playwright.sync_api import Page
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger

######################global########################
LOG_FORMAT = "[%(asctime)s][%(levelname)s][%(filename)s:%(funcName)s:%(lineno)d] %(message)s"
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
TOTAL_WORK_TIME = 180
TOTAL_COUNT= 0
one_work_time =30
#STEPS = 10
STEPS = 10
TOTAL_WORK_TIME_COUNT = 0
########################################################################
class CZTOUYU:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """
    def __init__(self,cookies_path: str, login_url: str, zhibo_url: str, watch_room_url: str, mp4_input_directory: str, only_msg):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.zhibo_url = zhibo_url
        self.watch_room_url = watch_room_url
        # playwright 部分
        self.browser = None
        self.input_directory = mp4_input_directory
        self.only_msg = only_msg
        # 微头条
        self.post_msg_url = None
        print("create CZTOUYU")

    def __del__(self):
        print("CZTOUYU is being destroyed")

    def login_or_restore_cookies(self) -> Page:
        """
          登录
        """
        context = self.browser.new_context()
        context.clear_cookies()
        page = context.new_page()
        page.goto(self.login_url)

        if os.path.exists(self.cookies_path):
            print("load cookies")
            # 从文件中加载 cookies
            with open(self.cookies_path, 'r',encoding='utf-8') as f:
                cookies = json.load(f)
            context.add_cookies(cookies)
            page.wait_for_timeout(3000)
        else:
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            time.sleep(60)
            cookies = page.context.cookies()
            with open(self.cookies_path, 'w',encoding='utf-8') as f:
                f.write(json.dumps(cookies))
        print("login_or_restore_cookies")
        return page
    
    def post_short_msg(self, page: Page, picture_path_list,habit_name:str, habit_detail:str):
        """
        发布图文
        """
        print("--------------------")
        page.goto("https://yuba.douyu.com/homepage/main")
        page.wait_for_timeout(3000)
        print("open https://yuba.douyu.com/homepage/main")
        # 点击--我关注的
        page.get_by_role("link", name="我关注的").click()
        page.wait_for_timeout(3000)
        print("我关注的")
        msg = habit_name + "\r\n"
        msg += habit_detail
        last = len(msg)
        if len(msg) - 100 > 0:
            last = len(msg) - 150
        content = msg[0:last]  # 长度有限制 导致无法发表内容
        # 填写内容
        # 鼠标移动
        print("模拟鼠标点击，让元素可用")
        page.locator("css=.editor__Ej48L.showplaceholder__uEYgz").click()
        page.wait_for_timeout(3000)
        print("模拟填写内容")
        page.locator("css=.editor__Ej48L").fill(content)
        page.wait_for_timeout(3000)

        # playwright codegen https://yuba.douyu.com/homepage/main
        print("开始上传图片")
        # page.get_by_text("图片").nth(0).click()
        # time.sleep(1)
        # for file_path in picture_path_list:
        #     with page.expect_file_chooser() as fc_info:
        #         page.locator("input[type=\"file\"]").click()
        #     file_chooser = fc_info.value
        #     file_chooser.set_files(file_path)
        #     time.sleep(30)
        # https://blog.csdn.net/m0_72775367/article/details/129040809

        with page.expect_file_chooser() as fc_info:
            page.get_by_text("图片/视频").click()
        file_chooser = fc_info.value
        file_chooser.set_files(picture_path_list)
        if platform.system() == "Windows":
           page.wait_for_timeout(60000)
        else:
            time.sleep(3) # 大图等待30秒
        print("结束上传图片")

        push_buttion = page.locator("css=.publishbtn__iG2In")
        push_buttion.hover()
        page.wait_for_timeout(3000)
        push_buttion.click()
        print("发布")
        page.wait_for_timeout(3000)
################################################
####################自动发帖###########################
def interface_auto_post_msg_douyu(file_path,habit_name,habit_detail):
    """
      对外调用接口
    """
    login_url = "https://www.douyu.com/"
    zhibo_url = "https://www.douyu.com/creator/main/live"
    watch_room_url = "https://www.douyu.com/11975253"
    post_msg_url = "https://yuba.douyu.com/homepage/main"
    sys = platform.system()
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\my_douyu_small.json"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/mp4/etc/my_douyu_small.json"
    else:
        cookies_path = r"/root/bin/my_douyu_small.json"
    print(cookies_path)
    autoupload = CZTOUYU(cookies_path, login_url, zhibo_url,watch_room_url,"","")
    autoupload.post_msg_url = post_msg_url
    try:
        with sync_playwright() as playwright:
            display_headless = False
            if platform.system() == "Linux":
                display_headless = True
                browser = playwright.chromium.launch(headless=display_headless)
            else:
                browser = playwright.chromium.launch(channel="chrome",headless=display_headless)
            autoupload.browser = browser
            login_page = autoupload.login_or_restore_cookies()
            # 发布图文
            autoupload.post_short_msg(login_page, file_path, habit_name,habit_detail)
    except Exception as mye:
        print(mye)
#############################################
def future_for_sleep():
    """
      每天写50字产品理解输出，10行代码
    """
    habit_detail = go_to_sleep.interface_go_to_sleep()
    random_images = get_pitcute.interface_get_three_pic()
    habit_name = "21点远离手机提醒"
    # 格式化为 年-月-日
    formatted_date = datetime.datetime.now().strftime('%Y-%m-%d')
    habit_name = formatted_date + " " + habit_name

    try:
        interface_auto_post_msg_douyu(random_images, habit_name, habit_detail)
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
if __name__ == '__main__':
    # playwright codegen https://yuba.douyu.com/
    future_for_sleep()
    job_defaults = {
        'coalesce': False,
        'max_instances': 1
    }
    # 调度器组件
    backsched = BlockingScheduler(job_defaults=job_defaults, timezone='Asia/Shanghai')
    # future_for_sleep callable函数 习惯养成--早睡早起
    # crontab 是 Linux 系统中用于设置周期性被执行的指令的命令
    # 0 0 * * *	每天的午夜（0 点）执行一次
    backsched.add_job(future_for_sleep, CronTrigger.from_crontab("30 21 * * *"), id="get_up")
    backsched.start()
